package com.bayss.core.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bayss.core.constant.ResultMsg;
import com.bayss.core.entity.found.*;
import com.bayss.core.entity.found.mapper.ZaihuMessageCommentsMapper;
import com.bayss.core.entity.found.mapper.ZaihuMessageLikeMapper;
import com.bayss.core.entity.found.mapper.ZaihuMessageMapper;
import com.bayss.core.entity.grade.Grade;
import com.bayss.core.entity.grade.mapper.GradeMapper;
import com.bayss.core.entity.order.OrderComment;
import com.bayss.core.entity.user.UserInfo;
import com.bayss.core.entity.user.mapper.UserInfoMapper;
import com.bayss.core.enums.MessageShow;
import com.bayss.core.enums.MessageStatus;
import com.bayss.core.model.ContentDetailVo;
import com.bayss.core.model.ContentVo;
import com.bayss.core.util.FileUtil;
import com.bayss.core.util.WeixinApi;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class FoundService {


    @Autowired
    private ZaihuMessageMapper zaihuMessageMapper;
    @Autowired
    private ZaihuMessageCommentsMapper zaihuMessageCommentsMapper;
    @Autowired
    private ZaihuMessageLikeMapper zaihuMessageLikeMapper;
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 发现，分页查询
     *
     * @param vo
     * @return
     */
    public PageInfo<ZaihuMessage> foundlistSearchTitleByPage(UserInfo userInfo, ZaihuMessageVo vo) {
        PageInfo<ZaihuMessage> result = PageHelper.startPage(vo.getPage(), vo.getSize()).doSelectPageInfo(() -> zaihuMessageMapper.foundlistSearchTitle(vo));
        if (result.getList() == null || result.getList().size() == 0) {
            return result;
        }

        //补充是否点过赞标识.登录状态的时候
        List<Integer> likeMessId = new ArrayList<>();
        if (userInfo != null && userInfo.getId() != null) {
            List<Integer> idList = result.getList().stream().map(ZaihuMessage::getId).collect(Collectors.toList());
            ZaihuMessageLikeExample example = new ZaihuMessageLikeExample();
            example.createCriteria().andUserIdEqualTo(userInfo.getId().intValue()).andMessageIdIn(idList);
            List<ZaihuMessageLike> likeList = zaihuMessageLikeMapper.selectByExample(example);
            likeMessId = likeList.stream().map(ZaihuMessageLike::getMessageId).collect(Collectors.toList());
        }

        for (ZaihuMessage m : result.getList()) {
            m.setContent(FileUtil.jsonDataImgUrl(m.getContent()));
            if (likeMessId.contains(m.getId())) {
                m.setIslike(1);
            }
        }
        return result;
    }

    /**
     * 订单评价同步到留言列表。如果有商铺评分，同时同步评分
     *
     * @param orderComment
     */
    public void addFoundMessageFromOrder(OrderComment orderComment) {
        try {
            ZaihuMessageVo vo = new ZaihuMessageVo();
            vo.setTitleName(orderComment.getGMsg());
            vo.setUserId(orderComment.getUid().intValue());

            JSONArray arr = JSONArray.parseArray(orderComment.getGGradeInfo());
            for (int i = 0; i < arr.size(); i++) {
                Integer id = arr.getJSONObject(i).getIntValue("id");
                String score = arr.getJSONObject(i).getString("score");
                Grade grade = gradeMapper.selectByPrimaryKey(id);
                if (grade != null && grade.getItemType().intValue() == 1) {
                    vo.setScore(score);
                    break;
                }
            }
            if ("0".equals(vo.getScore())) {
                return;//0分不同步
            }

            ContentVo contentVo = new ContentVo();
            contentVo.setTitleTitle(orderComment.getGMsg());
            if (!StringUtils.isBlank(orderComment.getGUrl())) {
                List<ContentDetailVo> uploadImg = new ArrayList<>();
                for (String url : orderComment.getGUrl().split(",")) {
                    ContentDetailVo detailVo = new ContentDetailVo();
                    detailVo.setUrl(url);
                    detailVo.setType("image");
                    uploadImg.add(detailVo);
                }
                contentVo.setUploadImg(uploadImg);
            }
            vo.setContent(JSONObject.toJSONString(contentVo));
            this.addfoundMessage(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 增加留言
     */
    @Transactional
    public ResultMsg addfoundMessage(ZaihuMessageVo vo) {
        if (StringUtils.isEmpty(vo.getTitleName())) {
            vo.setTitleName(vo.getContent());
        }

        WeixinApi weixin = new WeixinApi();
        boolean aa = weixin.msg_sec_check(vo.getTitleName());
        if (aa) {
            System.out.println("文字内容合法");
        } else {
            return new ResultMsg<>(false, 500, "内容含有违法违规内容");
        }
        JSONObject jsonObject = JSON.parseObject(vo.getContent());
        String titleTitle = jsonObject.getString("titleTitle");
        boolean aa1 = weixin.msg_sec_check(titleTitle);
        if (aa1) {
            System.out.println("文字内容合法");
        } else {
            return new ResultMsg<>(false, 500, "内容含有违法违规内容");
        }
        ZaihuMessage zaihuMessage = new ZaihuMessage();
        zaihuMessage.setContent(vo.getContent());
        zaihuMessage.setCreateTime(new Date());
        //修改此处，改为现身后发
        zaihuMessage.setMessageType(0);
        zaihuMessage.setPlaceTop(0);
        zaihuMessage.setTitleName(vo.getTitleName());
        zaihuMessage.setUserId(vo.getUserId());
        zaihuMessage.setScore(vo.getScore());
        //格式化url
        if (StringUtils.isNotEmpty(vo.getContent()) && vo.getContent().contains("doko")) {
            String jsonStr = JSONObject.parseObject(vo.getContent()).toJSONString();
            ContentVo contentVo = JSONObject.parseObject(jsonStr, ContentVo.class);
            for (ContentDetailVo d : contentVo.getUploadImg()) {
                d.setUrl(FileUtil.formatImgUrl(d.getUrl()));
            }
            zaihuMessage.setContent(JSONObject.toJSONString(contentVo));
        }
        zaihuMessageMapper.insertSelective(zaihuMessage);
        return ResultMsg.success("提交成功");
    }

    /**
     * 查询留言详情
     *
     * @param vo
     * @return
     */
    public ResultMsg findByfoundMessageId(ZaihuMessageVo vo) {
        ZaihuMessage zaihuMessage = zaihuMessageMapper.selectByPrimaryKey(vo.getId());
        if (zaihuMessage == null) {
            return new ResultMsg<>(false, 500, "留言不存在");
        }
        zaihuMessage.setContent(FileUtil.jsonDataImgUrl(zaihuMessage.getContent()));

        if (vo.getUserId() != null) {
            List<ZaihuMessageLike> zaihuMessageLikes = zaihuMessageLikeMapper.selectByUseridAndMessageid(vo);
            if (zaihuMessageLikes.size() > 0) {
                zaihuMessage.setIslike(1);
            }
        }
        return ResultMsg.success(zaihuMessage);
    }

    /**
     * 评论留言
     *
     * @param userInfo
     * @param vo
     * @return
     */
    @Transactional
    public synchronized ResultMsg commentsMessageforUser(UserInfo userInfo, ZaihuMessageVo vo) {
        if (vo.getComContent() != null && !vo.getComContent().equals("")) {
            WeixinApi weixin = new WeixinApi();
            boolean aa = weixin.msg_sec_check(vo.getComContent());
            if (aa) {
                System.out.println("文字内容合法");
            } else {
                return new ResultMsg<>(false, 500, "内容含有违法违规内容");
            }
        } else {
            return new ResultMsg<>(false, 500, "评论内容不能为空");
        }
        //更新留言评论数
        //zaihuMessageMapper.updateComentNumCream1(vo.getMessageId()); //评论审核后再更新评论数量

        //插入评论
        ZaihuMessageComments zaihuMessageComments = new ZaihuMessageComments();
        zaihuMessageComments.setComContent(vo.getComContent());
        zaihuMessageComments.setComType(MessageShow.show);
        zaihuMessageComments.setCreateTime(new Date());
        zaihuMessageComments.setMessageId(vo.getMessageId());
        zaihuMessageComments.setUserId(vo.getUserId());
        ZaihuMessage zaihuMessage = zaihuMessageMapper.selectByPrimaryKey(vo.getMessageId());
        UserInfo messageUser = userInfoMapper.selectByPrimaryKey(zaihuMessage.getUserId().longValue());
        messageUser = messageUser==null?new UserInfo():messageUser;
        zaihuMessageComments.setCreator(messageUser.getNickname());
        zaihuMessageComments.setCreatorUrl(messageUser.getHeadPortraitUrl());
        ContentVo contentVo = JSONObject.parseObject(zaihuMessage.getContent(), ContentVo.class);
        zaihuMessageComments.setTitleName(contentVo.getTitleTitle());
        zaihuMessageComments.setStatus(MessageStatus.waitCheck.getVal());
        zaihuMessageCommentsMapper.insertSelective(zaihuMessageComments);
        return ResultMsg.success("添加评论成功");
    }

    /**
     * 点赞留言
     */
    @Transactional
    public synchronized ResultMsg likeMessageforUser(ZaihuMessageVo vo) {
        List<ZaihuMessageLike> zaihuMessageLikes = zaihuMessageLikeMapper.selectByUseridAndMessageid(vo);
        if (zaihuMessageLikes.size() > 0) {
            return ResultMsg.success("点赞成功");
        }
        //更新点赞次数
        zaihuMessageMapper.updatelikeNumCream1(vo.getMessageId());
        //记录点赞记录
        ZaihuMessageLike zaihuMessageLike = new ZaihuMessageLike();
        zaihuMessageLike.setCreateTime(new Date());
        zaihuMessageLike.setMessageId(vo.getMessageId());
        zaihuMessageLike.setUserId(vo.getUserId());
        zaihuMessageLikeMapper.insertSelective(zaihuMessageLike);
        return ResultMsg.success("点赞成功");
    }

    /**
     * 查询评论列表
     */
    public ResultMsg commentslist(ZaihuMessageVo vo) {
        PageInfo<ZaihuMessageComments> result = PageHelper.startPage(vo.getPage(), vo.getSize()).doSelectPageInfo(() -> zaihuMessageCommentsMapper.selectByMesageId(vo.getMessageId(), vo.getStatus()));
        return ResultMsg.success(result);
    }

    /**
     * 点赞列表
     *
     * @param vo
     * @return
     */
    public ResultMsg likeslist(ZaihuMessageVo vo) {
        PageInfo<ZaihuMessageLike> result = PageHelper.startPage(vo.getPage(), vo.getSize()).doSelectPageInfo(() -> zaihuMessageLikeMapper.selectByZaihuMessageLikes(vo));
        return ResultMsg.success(result);
    }


    /**
     * 删除留言
     *
     * @param messageId
     * @return
     */
    @Transactional
    public ResultMsg deleteByMessageId(Integer messageId) {
        zaihuMessageMapper.deleteByPrimaryKey(messageId);
        //删除点赞和评论
        this.deleteMessageComments(messageId);
        this.deleteMessageLikes(messageId);
        return ResultMsg.success();
    }

    /**
     * 根据留言id删除评论列表
     *
     * @param messageId
     */
    private void deleteMessageComments(Integer messageId) {
        ZaihuMessageCommentsExample example = new ZaihuMessageCommentsExample();
        example.createCriteria().andMessageIdEqualTo(messageId);
        zaihuMessageCommentsMapper.deleteByExample(example);
    }

    /**
     * 根据留言id删除点赞列表
     *
     * @param messageId
     */
    private void deleteMessageLikes(Integer messageId) {
        ZaihuMessageLikeExample example = new ZaihuMessageLikeExample();
        example.createCriteria().andMessageIdEqualTo(messageId);
        zaihuMessageLikeMapper.deleteByExample(example);
    }

    /**
     * 根据评论id删除评论
     *
     * @param id
     * @return
     */
    @Transactional
    public ResultMsg deleteByComentId(Integer id) {
        ZaihuMessageComments zaihuMessageComments = zaihuMessageCommentsMapper.selectByPrimaryKey(id);
        if (zaihuMessageComments != null) {
            zaihuMessageMapper.updateComentNumdecrease1(zaihuMessageComments.getMessageId());
            zaihuMessageCommentsMapper.deleteByPrimaryKey(id);
        }
        return ResultMsg.success();
    }


    /**
     * 取消点赞
     *
     * @param vo
     * @return
     */
    @Transactional
    public synchronized ResultMsg cancelLike(ZaihuMessageVo vo) {
        //删除点赞记录
        ZaihuMessageLike zaihuMessageLike = new ZaihuMessageLike();
        zaihuMessageLike.setMessageId(vo.getMessageId());
        zaihuMessageLike.setUserId(vo.getUserId());
        zaihuMessageLikeMapper.deleteByMessageIdAndUserid(zaihuMessageLike);
        ZaihuMessage zaihuMessage = zaihuMessageMapper.selectByPrimaryKey(vo.getMessageId());
        if (zaihuMessage.getLikeNum() != null && zaihuMessage.getLikeNum() > 0) {
            zaihuMessageMapper.updatelikeNumdecrease1(vo.getMessageId());
        }
        return new ResultMsg<>(true, 200, null);
    }

    /**
     * 查询用户的评论列表
     *
     * @param vo
     * @return
     */
    public ResultMsg commentMylist(ZaihuMessageVo vo) {
        ZaihuMessageCommentsExample example = new ZaihuMessageCommentsExample();
        example.createCriteria().andUserIdEqualTo(vo.getUserId());

        PageInfo<ZaihuMessageComments> result = PageHelper.startPage(vo.getPage(), vo.getSize()).doSelectPageInfo(() -> zaihuMessageCommentsMapper.selectByExample(example));
        return ResultMsg.success(result);
    }


}
